#!/bin/bash

# Rainbond Console Java API 测试脚本

BASE_URL="http://localhost:8000"
CONTENT_TYPE="Content-Type: application/json"

echo "🚀 开始测试 Rainbond Console Java API..."
echo "Base URL: $BASE_URL"
echo

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 测试健康检查
echo "📊 测试健康检查..."
curl -s "$BASE_URL/actuator/health" | jq . 2>/dev/null || echo "健康检查失败或jq未安装"
echo

# 测试登录
echo "🔐 测试用户登录..."
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/api/auth/login" \
  -H "$CONTENT_TYPE" \
  -d '{
    "nickName": "admin",
    "password": "admin123"
  }')

echo "登录响应: $LOGIN_RESPONSE"
echo

# 提取token
TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.data.token' 2>/dev/null)

if [ "$TOKEN" = "null" ] || [ -z "$TOKEN" ]; then
    echo "❌ 登录失败，无法获取token"
    echo "请确保应用已启动并且默认用户已创建"
    exit 1
fi

echo "✅ 登录成功，Token: ${TOKEN:0:50}..."
echo

# 测试用户列表（需要管理员权限）
echo "👥 测试获取用户列表..."
curl -s -X GET "$BASE_URL/api/users" \
  -H "$CONTENT_TYPE" \
  -H "Authorization: GRJWT $TOKEN" | jq . 2>/dev/null || echo "获取用户列表失败"
echo

# 测试检查用户存在
echo "🔍 测试检查用户是否存在..."
curl -s -X GET "$BASE_URL/api/auth/check-user/admin" \
  -H "$CONTENT_TYPE" | jq . 2>/dev/null || echo "检查用户失败"
echo

# 测试登出
echo "🚪 测试用户登出..."
curl -s -X POST "$BASE_URL/api/auth/logout" \
  -H "$CONTENT_TYPE" \
  -H "Authorization: GRJWT $TOKEN" | jq . 2>/dev/null || echo "登出失败"
echo

# 测试Swagger文档
echo "📚 测试API文档..."
curl -s "$BASE_URL/swagger-ui.html" > /dev/null && echo "✅ Swagger UI 可访问: $BASE_URL/swagger-ui.html" || echo "❌ Swagger UI 无法访问"
echo

echo "🎉 API测试完成！"
echo
echo "📖 可用的API端点："
echo "  - 登录: POST $BASE_URL/api/auth/login"
echo "  - 登出: POST $BASE_URL/api/auth/logout"
echo "  - 用户列表: GET $BASE_URL/api/users"
echo "  - 检查用户: GET $BASE_URL/api/auth/check-user/{username}"
echo "  - API文档: $BASE_URL/swagger-ui.html"
echo "  - H2控制台: $BASE_URL/h2-console"
echo
echo "🔑 默认管理员账号："
echo "  用户名: admin"
echo "  密码: admin123"





